<?php
/**
 * Category controller
 *
 * @uses       Zend_Controller_Action
 * @package    FireFeed
 * @subpackage Controller
 */
class CategoryController extends Zend_Controller_Action 
{
	/**
	 * @var Zend_Translate
	 */
	private $_translate;
	
	public function init()
	{
		$this->_translate = Zend_Registry::get('Zend_Translate');
	}
	 	
    /**
     * Reatrieve all categories and return in Json format
     * - Ajax action
     * 
     * @return void
     */
    public function loadcategoriesAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $factory = Model_Factory::getInstance();
        $service = $factory->getCategoryService();
        $categories = $service->getCategories();
        
        $resultArray = array();
        
        foreach ($categories as $category) {
            $result = $category->getOptions();
            
            unset($result['description']);
            unset($result['feeds']);
            unset($result['createdBy']);
            unset($result['owners']);
            
            $resultArray[] = $result;
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Reatrieve all user categories and return in Json format
     * - Ajax action
     * 
     * @return void
     */
    public function loadusercategoriesAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $factory = Model_Factory::getInstance();
        $service = $factory->getCategoryService();
        $userID = Zend_Auth::getInstance()->getIdentity()->oid;
        $categories = $service->getUserCategories($userID);
        
        $resultArray = array();
        
        foreach ($categories as $category) {
            $result = $category->getOptions();
            
            unset($result['description']);
            unset($result['feeds']);
            unset($result['createdBy']);
            unset($result['owners']);
            
            $resultArray[] = $result;
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Load addcategory form 
     * 
     * @return void
     */
    public function activeaddcategoryAction()
    {
        $this->_helper->layout->disableLayout();
        
        $this->view->formAddCategory = new Form_Category();
    }
    
    /**
     * Save the submitted category
     * - Ajax action
     * @return void
     */
    public function addcategoryAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost();
            $form = new Form_Category();
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                $factory = Model_Factory::getInstance();
                $service = $factory->getCategoryService();
                $user = Zend_Auth::getInstance()->getIdentity();
                $category = new Model_Entity_Category($form->getValues());
                $category->setCreatedBy($user);
                
                $service->addCategory($category);
            } else {
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else {
            $this->_forward('activeaddcategory');
        }
    }
    
    /**
     * Save the submitted user category
     * - Ajax action
     * @return void
     */
    public function addusercategoryAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost();
            $form = new Form_Category();
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                $factory = Model_Factory::getInstance();
                $service = $factory->getCategoryService();
                $user = Zend_Auth::getInstance()->getIdentity();
                $category = new Model_Entity_Category($form->getValues());
                $category->setCreatedBy($user);
                
                $service->addUserCategory($category);
            } else {
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else {
            $this->_forward('activeaddcategory');
        }
    }
    
    /**
     * Loads the history categories page
     * - Ajax action
     * 
     * @return void
     */
    public function loadcategorieshistoryAction()
    {
        $this->_helper->layout->disableLayout();
        
        $userID = Zend_Auth::getInstance()->getIdentity()->oid;
        $arrayVal = array(''=>'all', $userID=>'mine');
        
        $form = new Form_CategoryHistory();
        $form->getElement('owner')->setMultiOptions($arrayVal);
        $this->view->categoryHistoryForm = $form;
    }
    
    /**
     * Reatrieve all categories and render them in a list
     * - Ajax action
     * 
     * @return void
     */
    public function loadcategorieslistAction()
    {
    	$searchSession = new Zend_Session_Namespace('searchcat');
    	
        $this->_helper->layout->disableLayout();
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $form = new Form_CategoryHistory();
            $post = $request->getPost();

            if ($form->isValid($post)) {
                $values = $form->getValues();
                
                $factory = Model_Factory::getInstance();
                $service = $factory->getCategoryService();
                
                if (0 == $this->_getParam('page', 0)) {
                	$searchSession->unsetAll();
                	$searchSession->userID = $form->getValue('owner');
                	$searchSession->contains = $form->getValue('contains');
                }
                
                $criteria = array();
                $criteria['userID'] = $searchSession->userID;
                $criteria['contains'] = $searchSession->contains;
                
                $categories = new Zend_Paginator($service->searchCategories($criteria));
                $categories->setCurrentPageNumber($this->_getParam('page', 1));
                $categories->setItemCountPerPage(5);
                $categories->setPageRange(5);
                
                $this->view->categories = $categories;
            } else {
                $this->getResponse()->appendBody("form non valido");
            }
        }
    }
    
    /**
     * Load the category editing form 
     * - Ajax action
     * 
     * @return void
     */
    public function activeupdateusercategoryAction()
    {
    	$this->_helper->layout->disableLayout();
    	
    	$catID = $this->_getParam('catID');
    	
    	if (!empty($catID) && is_numeric($catID) && ($catID > 0)) {
	    	$factory = Model_Factory::getInstance();
	        $service = $factory->getCategoryService();
	        
	        $serachCat = new Model_Entity_Category();
	        $serachCat->setOid($catID);
	        $serachCat->setOwners(Zend_Auth::getInstance()->getIdentity());
	        
	        $category = $service->getCategory($serachCat);
	
	        $form = new Form_Category();
	        $form->populate($category->getOptions());
	        
	        $this->view->formCategory = $form;
    	} else {
    		$this->_helper->viewRenderer->setNoRender();
    		$message = $this->_translate->translate('invalidparam');
    		$this->_response->appendBody($message);
    	}
    }
    
    /**
     * Update category informations
     * - Ajax action
     * 
     * @return void
     */
    public function updateusercategoryAction()
    {
    	$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            $form = new Form_Category();
            $post = $request->getPost();

            if ($form->isValid($post)) {
                $values = $form->getValues();
                
                $factory = Model_Factory::getInstance();
                $service = $factory->getCategoryService();
                
                $category = new Model_Entity_Category($form->getValues());
                $category->setOwners(Zend_Auth::getInstance()->getIdentity());
                
                $service->updateUserCategory($category);
            } else {
            	$messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        }
    }
    
    /**
     * Delete a user category
     * - Ajax action
     * 
     * @return void
     */
    public function deleteusercategoryAction()
    {
    	$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $catID = $this->_getParam('elementID');
        if (!empty($catID) && is_numeric($catID) && ($catID > 0)) {
	        $factory = Model_Factory::getInstance();
	        $service = $factory->getCategoryService();
	        
	        $category = new Model_Entity_Category();
	        $category->setOid($catID);
	        $category->setOwners(Zend_Auth::getInstance()->getIdentity());
	        
	        try {
	            $service->deleteUserCategory($category);
	        } catch (Model_ZendDb_CantDeleteException $e) {
	        	$message = $this->_translate->translate('cathasfeeds');
                $resultArray = array('error' => true,
                                     'message' => $message);
	        }
        } else {
        	$message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Delete a category
     * - Ajax action
     * 
     * @return void
     */
    public function deletecategoryAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $catID = $this->_getParam('elementID');
        if (!empty($catID) && is_numeric($catID) && ($catID > 0)) {
            $factory = Model_Factory::getInstance();
            $service = $factory->getCategoryService();
            
            $category = new Model_Entity_Category();
            $category->setOid($catID);
            
            try {
                $service->deleteCategory($category);
            } catch (Model_ZendDb_CantDeleteException $e) {
                $message = $this->_translate->translate('cantdelete');
                $resultArray = array('error' => true,
                                     'message' => $message);
            }
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Set a given category as interesting for a given user
     * - Ajax action
     * 
     * @return void
     */
    public function setcategoryofinterestAction()
    {
    	$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $catID = $this->_getParam('elementID');
        if (!empty($catID) && is_numeric($catID) && ($catID > 0)) {
        	$factory = Model_Factory::getInstance();
            $service = $factory->getCategoryService();
            $userID = Zend_Auth::getInstance()->getIdentity()->oid;
            
            $service->setCategoryOfInterest($catID, $userID);
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Unset a given category as interesting for a given user
     * - Ajax action
     * 
     * @return void
     */
    public function unsetcategoryofinterestAction()
    {
    	$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $catID = $this->_getParam('elementID');
        if (!empty($catID) && is_numeric($catID) && ($catID > 0)) {
            $factory = Model_Factory::getInstance();
            $service = $factory->getCategoryService();
            $userID = Zend_Auth::getInstance()->getIdentity()->oid;
            
            $service->removeCategoryOfInterest($catID, $userID);
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
}
